import Vue from 'vue'
import App from './App'
import store from './store';
Vue.prototype.$store = store
import zwyList from '@/components/zwyList.vue';
Vue.component('zwyList', zwyList);

import navTop from '@/components/navTop.vue';
Vue.component('navTop', navTop);

import navTopIndex from '@/components/navTopIndex.vue';
Vue.component('navTopIndex', navTopIndex);

import navTopTT from '@/components/navTopTT.vue';
Vue.component('navTopTT', navTopTT);

import navTopIndexTT from '@/components/navTopIndexTT.vue';
Vue.component('navTopIndexTT', navTopIndexTT);

import navTab from '@/components/navTab.vue';
Vue.component('navTab', navTab);


import zwyLoading from '@/components/zwyLoading.vue';
Vue.component('zwyLoading', zwyLoading);

import noData from '@/components/noData.vue';
Vue.component('noData', noData);


import zwyPopupAll from '@/components/zwyPopupAll.vue';
Vue.component('zwyPopupAll', zwyPopupAll);

Vue.config.productionTip = false

App.mpType = 'app'


import uma from './util/uma'

Vue.prototype.$uma = uma;

import * as zwyFilter from './util/zwyFilter.js'

// 抖音配置
let ttConfig = require("./util/ttConfigSet.js");
// 快手配置
let ksConfigAll = require("./util/tempConfig.js");

Object.keys(zwyFilter).forEach(key => {
	Vue.filter(key, zwyFilter[key])
})
// #ifdef MP-TOUTIAO
	Vue.prototype.clientName = 'MP-TOUTIAO';
	Vue.prototype.moneyName = 'K币';

	let ttAccountInfo = tt.getEnvInfoSync() && tt.getEnvInfoSync().microapp
	let ttConfigMess = null
	if(ttAccountInfo && ttAccountInfo.appId) {
		ttConfigMess = ttConfig[ttAccountInfo.appId]
	}
// #endif

// #ifdef MP-KUAISHOU
	Vue.prototype.clientName = 'MP-KUAISHOU';
	Vue.prototype.moneyName = '看币';
// #endif



Vue.prototype.cleanWatchWord = function(){
	let watchword = uni.getStorageSync('watchword');
	if(watchword && uni.setClipboardData){
		uni.setClipboardData({
			data: '',
			success: res => {
			},
			fail: res => {
			},
			complete:res=>{
				uni.hideToast();
			}
		});
	}
}

Vue.prototype.setWatchWord = function(){
	let watchword = uni.getStorageSync('watchword');
	console.log(`
		watchword：${watchword},
		uni.setClipboardData:${uni.setClipboardData}
	`)
	if(watchword && uni.setClipboardData){
		uni.setClipboardData({
			data: watchword,
			success: res => {
				uni.setStorageSync('hasSetClip', true);
				uni.setStorageSync('clipUrl',watchword);
				if(!getApp().globalData['Ume_password_copy_win']){
					console.log('口令复制成功');
					this.$uma && this.$uma.trackEvent('Ume_password', {
						name: 'Ume_password_copy_win'
					});
					getApp().globalData['Ume_password_copy_win']  = true;
				}
				if(watchword.indexOf('kuaishou.com') != -1){
					// 服务号口令复制
					if(!getApp().globalData['Ume_password_copy_SN']){
						console.log('服务号口令复制');
						this.$uma && this.$uma.trackEvent('Ume_password', {
							name: 'Ume_password_copy_SN'
						});
						getApp().globalData['Ume_password_copy_SN']  = true;
					}
					
				}else {
					// 小程序口令复制
					if(!getApp().globalData['Ume_password_copy_APP']){
						console.log('小程序口令复制');
						this.$uma && this.$uma.trackEvent('Ume_password', {
							name: 'Ume_password_copy_APP'
						});
						getApp().globalData['Ume_password_copy_APP']  = true;
					}
				}
			},
			fail: res => {
				if(!getApp().globalData['Ume_password_copy_Defeat']){
					console.log('小程序口令复制失败');
					this.$uma && this.$uma.trackEvent('Ume_password', {
						name: 'Ume_password_copy_Defeat'
					});
					getApp().globalData['Ume_password_copy_Defeat']  = true;
				}
			},
			complete:res=>{
				uni.hideToast();
			}
		});
	}
}

Vue.prototype.getBindFollowStatus = function(appId) {
	return new Promise((resolve, reject) => {
		if(!appId) resolve(false)
		if (getApp().globalData.config) {
			resolve(getApp().globalData.config);
			return;
		}

		this.zwyRequest({
			method: 'GET',
			url: "/user/thirdpart_binding/isUserSubscribeOfficalAccountByOpenId",
			"contentType": 'application/json;charset=utf-8',
			"data": {
				appId: appId
			},
		}).then(res => {
			console.log('------res', res)
			if(res && res == 1) {
				resolve(true)
			} else {
				resolve(false)
			}
		}).catch(err => {
			reject(err)
		})
	})
},

Vue.prototype.postActive = function(type){
	// 添加24小时只能回传一次
	let alreadyBackCall = uni.getStorageSync('alreadyBackCall') || {}
	console.log('alreadyBackCall', alreadyBackCall)
	if(alreadyBackCall && alreadyBackCall.timeStep) {
		let nowDate = new Date()
		let config = timeChangeSet(nowDate, alreadyBackCall.timeStep)
		console.log('config-----', config)
		if(config.days < 1) {
			return 
		}
	}
	
	let tempE = uni.getStorageSync('enterPath');
	tempE = JSON.parse(tempE);
	console.log('postActiveConfig111111', type)
	console.log('postActiveConfig222222', tempE)
	if (tempE && tempE.query && tempE.query.callback) {
		if(type === 'order') { //订单清除定时器立即执行
			getApp().globalData.activeTimer = null
		}
		if(getApp().globalData.activeTimer) return;
		this.getConfig().then(res => {
			console.log('postActiveConfig', res);
			let statisTime = 0;
			if(type === 'order') {
				statisTime = 10;
			} else {
				statisTime = 1 || 500000;
			}
			 
			getApp().globalData.activeTimer = setTimeout(() => {
				this.zwyRequest({
					url: '/blade/ks/active',
					method: 'POST',
					data: tempE.query,
					noErr: true
				}).then(res2=>{
					// #ifdef MP-KUAISHOU
					this.ksWare(tempE.query)
					uni.setStorageSync('alreadyBackCall', {
						timeStep: new Date(),
						status: true
					})
					// #endif
					getApp().globalData.activeTimer = null
					console.log('postActive/blade/ks/activeSuccess');
				})
			}, statisTime);
			return;
		});
	}
}

Vue.prototype.postActiveDy = function(type){
	let tempE = uni.getStorageSync('enterPath');
	tempE = JSON.parse(tempE);
	if (tempE && tempE.query && tempE.query.batchId) {
		if(type === 'order') { //订单清除定时器立即执行
			getApp().globalData.activeTimer = null
		}
		if(getApp().globalData.activeTimer) return;
		this.getConfig().then(res => {
			setTimeout(() => {
				this.zwyRequest({
					url: '/blade/ks/active',
					method: 'POST',
					data: tempE.query,
					noErr: true
				}).then(res2=>{
					getApp().globalData.activeTimer = null
					console.log('postActive/blade/ks/activeSuccess');
				})
			}, 3000);
		});
	}
}

// 唤端接口
Vue.prototype.ksWare = function(data) {
	this.zwyRequest({
		url: '/blade/ks/wake',
		method: 'POST',
		data: data,
		noErr: true
	}).then(res2=>{
		console.log('blade/ks/wake', res2)
		console.log('blade/ks/wake');
	})
}


Vue.prototype.noDataAndBack  = async function(showMsg = true){
    setTimeout(() => {
        let page = getCurrentPages();
        if (page.length <= 1) {
            uni.switchTab({
                url: '/pages/fx_xjc/fx_xjc'
            });
            return;
        }
    
        uni.navigateBack({
            delta: 1,
            fail: res => {
                uni.switchTab({
                    url: '/pages/fx_xjc/fx_xjc'
                });
				return;
            }
        })
    }, showMsg ? 1000 : 0);
    if (showMsg) {
        uni.showToast({
            title: '数据异常，请重试！',
            icon: 'none'
        })
    }
    return;
}

Vue.prototype.$disabledScreenRecord  = async function(){
	console.log('uni.getSystemInfoSync()',uni.getSystemInfoSync());
	let model = uni.getSystemInfoSync()['model'];
	console.log('model',model.indexOf('iPhone'));
	let isIos = model.indexOf('iPhone') != -1 ;
	console.log('isIos',isIos);
	let res = '';
	if(isIos){
		uni.onUserScreenRecord(()=>{});
	}else{
		try{
				res= await uni.disableUserScreenRecord({
					success:(resSuccess)=>{
						console.log('安卓截屏监听success' + JSON.stringify(resSuccess));
					},
					fail:(resFail)=>{
						console.log('安卓截屏监听fail' + resFail);
					},
					complete:(resComplete)=>{
						console.log('安卓截屏监听complete',resComplete);
					}
				})
		}catch(e){
			//TODO handle the exception
			console.log('不支持录屏',e);
		}
	}
	console.log('api调用结果:' + res);
}




Vue.prototype.$statis = async function(data) {
	let pages = getCurrentPages(); //获取加载的页面
	let currentPage = pages[pages.length - 1]; //获取当前页面的对象
	let url = currentPage.route; //当前页面url
	console.log('url', url);
	let systemInfo = await uni.getSystemInfoSync();
	let userInfo = uni.getStorageSync('userInfo');

	let postData = {
		page: url,
		position:data.position ? data.position : url,
		userAgent: systemInfo['model'],
		'appId': uni.getStorageSync('appId') || '',
		data: JSON.stringify(data),
		dataList: [data],
		dataSource: "DISTRIBUTION_PLATFORM",
		rlScene: "origin",
		shareUser: '0',
		source: "",
		userId: userInfo ? String(userInfo.userId) : '0',
		weiXinUserId: userInfo ? String(userInfo.userId) : '0',
		'scene': String(getApp().globalData.scene),
		...data
	}
	clearTimeout(getApp().globalData.statisTimer);
	getApp().globalData.statisTimer = '';
	getApp().globalData.statisPostData.push(postData);
	let testCheck = getApp().globalData.attributeServerApi || false;

	let tempUrl = testCheck ? '/attribute_server_api/mini_app_data/test/add' :
		'/attribute_server_api/mini_app_data/add';

	let headerObj = {
		action: postData.action,
		page: url,
		position: url
	}

	if(getApp().globalData.templateMessageTaskId && getApp().globalData.templateMessageTaskType) {
		headerObj['template-message-task-id'] = getApp().globalData.templateMessageTaskId
		headerObj['template-message-task-type'] = getApp().globalData.templateMessageTaskType
	}

	if(getApp().globalData.chainId) {
		headerObj['chain-id'] = getApp().globalData.chainId
	}
	getApp().globalData.statisTimer = setTimeout(() => {
		this.zwyRequest({
			method: 'POST',
			url: tempUrl,
			header: headerObj,
			data: JSON.stringify(getApp().globalData.statisPostData),
		}).then(res => {
			getApp().globalData.statisPostData = [];
		})
	}, 2000);
}
Vue.prototype.$statisAd = async function(data) {
	let pages = getCurrentPages(); //获取加载的页面
	let currentPage = pages[pages.length - 1]; //获取当前页面的对象
	let url = currentPage.route; //当前页面url
	console.log('url', url);
	let systemInfo = await uni.getSystemInfoSync();
	let userInfo = uni.getStorageSync('userInfo');

	let postData = {
		page: url,
		position: url,
		userAgent: systemInfo['model'],
		'appId': uni.getStorageSync('appId') || '',
		data: JSON.stringify(data),
		dataList: [data],
		dataSource: "DISTRIBUTION_PLATFORM",
		rlScene: "origin",
		shareUser: '0',
		source: "",
		userId: userInfo ? String(userInfo.userId) : '0',
		weiXinUserId: userInfo ? String(userInfo.userId) : '0',
		'scene': String(getApp().globalData.scene),
		...data
	}
	clearTimeout(getApp().globalData.statisTimer);
	getApp().globalData.statisTimer = '';
	getApp().globalData.statisPostDataAd.push(postData);
	let testCheck = getApp().globalData.attributeServerApi || false;

	let tempUrl = '/attribute_server_api/mini_app_data/miniapp/ad/add';

	let headerObj = {
		action: postData.action,
		page: url,
		position: url
	}

	if(getApp().globalData.templateMessageTaskId && getApp().globalData.templateMessageTaskType) {
		headerObj['template-message-task-id'] = getApp().globalData.templateMessageTaskId
		headerObj['template-message-task-type'] = getApp().globalData.templateMessageTaskType
	}

	if(getApp().globalData.chainId) {
		headerObj['chain-id'] = getApp().globalData.chainId
	}
	getApp().globalData.statisTimer = setTimeout(() => {
		this.zwyRequest({
			method: 'POST',
			url: tempUrl,
			header: headerObj,
			data: JSON.stringify(getApp().globalData.statisPostDataAd),
		}).then(res => {
			getApp().globalData.statisPostDataAd = [];
		})
	}, 500);
}
Vue.prototype.clientInfo = {
	//#ifdef MP-KUAISHOU
	'loginUrl': '/user/kuaishou_login/kuaishou_mini_program?accountType=PRODUCT_ACCOUNT',
	'client-id-test': '21',
	'urlObj-test': {
		'mp-api': 'https://mp-component-test.qiguoread.com',
		'cdp': 'https://cdptest.qiguoread.com',
		'user': 'https://usertest.qiguoread.com',
		'wealth': 'https://wealthtest.qiguoread.com',
		'welfare': 'https://minitest.qiguoread.com',
		'attribute_server_api': 'https://attribute-test.qiguoread.com',
		'blade': 'https://bladetest.qiguoread.com',
		'report': 'https://reporttest.qiguoread.com'
	},
	'urlObj-online': {
		'mp-api': 'https://mp-component.qiguoread.com',
		'cdp': 'https://cdp.qiguoread.com',
		'user': 'https://user.qiguoread.com',
		'wealth': 'https://wealth.qiguoread.com',
		'welfare': 'https://mini.qiguoread.com',
		'attribute_server_api': 'https://attribute-server.qiguoread.com',
		'blade': 'https://blade.qiguoread.com',
		'report': 'https://report.qiguoread.com'
	},
	'urlObj-qa': {
		'mp-api': 'https://component.qa.qiguoread.com',
		'cdp': 'https://cdp.qa.qiguoread.com',
		'user': 'https://user.qa.qiguoread.com',
		'wealth': 'https://wealth.qa.qiguoread.com',
		'welfare': 'https://mini.qa.qiguoread.com',
		'attribute_server_api': 'https://attribute.qa.qiguoread.com',
		'blade': 'https://blade.qa.qiguoread.com',
		'report': 'https://report.qiguoread.com'
	},
	'c-type': '5',
	//#endif

	//#ifdef MP-TOUTIAO
		'loginUrl': '/user/douyin/mini_program/login?accountType=PRODUCT_ACCOUNT',
		'client-id-online': ttConfigMess ? ttConfigMess.onlineId : '43', // 38:海洋短剧  42:剧多多 43:果果剧场
		'client-id-test': ttConfigMess ? ttConfigMess.devId : '28', // 23:海洋测试 27：剧多多测试 28：果果剧场
		'urlObj-test': {
			'mp-api': 'https://mp-component-test.qiguoread.com',
			'cdp': 'https://cdptest.qiguoread.com',
			'user': 'https://usertest.qiguoread.com',
			'wealth': 'https://wealthtest.qiguoread.com',
			'welfare': 'https://minitest.qiguoread.com',
			'attribute_server_api': 'https://attribute-test.qiguoread.com',
			'blade': 'https://bladetest.qiguoread.com',
			'douYin':'https://dytest.qiguoread.com',
			'report': 'https://report.qiguoread.com'
		},
		'urlObj-online': {
			'mp-api': 'https://mp-component.qiguoread.com',
			'cdp': 'https://cdp.qiguoread.com',
			'user': 'https://user.qiguoread.com',
			'wealth': 'https://wealth.qiguoread.com',
			'welfare': 'https://mini.qiguoread.com',
			'attribute_server_api': 'https://attribute-server.qiguoread.com',
			'blade': 'https://blade.qiguoread.com',
			'douYin':'https://dy.qiguoread.com',
			'report': 'https://report.qiguoread.com'
		},
		'urlObj-qa': {
			'mp-api': 'https://component.qa.qiguoread.com',
			'cdp': 'https://cdp.qa.qiguoread.com',
			'user': 'https://user.qa.qiguoread.com',
			'wealth': 'https://wealth.qa.qiguoread.com',
			'welfare': 'https://mini.qa.qiguoread.com',
			'attribute_server_api': 'https://attribute.qa.qiguoread.com',
			'blade': 'https://blade.qa.qiguoread.com',
			'douYin':'https://dy.qa.qiguoread.com',
			'report': 'https://report.qiguoread.com'
		},
		'app-id': ttConfigMess ? ttConfigMess.appId : 'ttce10b8ad512e3bd801', // 海洋短剧:tt8032f68f1f0ba85501  剧多多:tt58602eddc7597c0c01  果果剧场:ttce10b8ad512e3bd801
		'c-type': '6',
	//#endif
}


Vue.prototype.zwyLogin = function() {
	getApp().globalData.loginTimes++;
	if (getApp().globalData.loginTimes > 5) {
		uni.showToast({
			title: '登陆次数到达上限',
			icon: 'none'
		})
		// getApp().globalData.loginTimes = 0;
		setTimeout(() => {
			getApp().globalData.loginTimes = 0;
		}, 5000)
		return;
	}
	getApp().globalData.isLogining = true;
	return new Promise((resolve, reject) => {
		uni.login({
			success: (loginRes) => {
				console.log('loginRes.code', loginRes.code);
				this.zwyRequest({
					url: this.clientInfo.loginUrl,
					data: {
						//#ifdef MP-TOUTIAO
						code: loginRes.code,
						// #endif
						//#ifdef MP-KUAISHOU
						jsCode: loginRes.code
						//#endif
					},
					method: 'POST',
				}).then((res) => {
					console.log('zwyLogin', res);
					if (typeof res == 'object') {
						uni.setStorageSync('userInfo', res);
						// uni.setStorageSync('alreadyAuthLogin', res.authUserDTO.iconUrl ? true : false);
						console.log('getApp().globalData.zwyQueue', getApp().globalData
							.zwyQueue);
						let zwyQueue = getApp().globalData.zwyQueue;
						if (zwyQueue.length > 0) {
							for (let i = 0; i < zwyQueue.length; i++) {
								this.zwyRequest(zwyQueue[i]);
							}
							getApp().globalData.zwyQueue = [];
						}
					} else {
						getApp().globalData.loginFail = getApp().globalData.loginFail +
							1;
						console.log('getApp().globalData.loginFail', getApp().globalData
							.loginFail);
						if (getApp().globalData.loginFail < 3) {
							this.zwyLogin();
						} else {
							// let zwyQueue = getApp().globalData.zwyQueue;
							// if (zwyQueue.length > 0) {
							// 	for (let i = 0; i < zwyQueue.length; i++) {
							// 		this.zwyRequest(zwyQueue[i]);
							// 	}
							// 	getApp().globalData.zwyQueue = [];
							// }
						}
					}
					getApp().globalData.isLogining = false;
					resolve();
				})
			},
			fail() {
				getApp().globalData.isLogining = false;
			}
		});
	})
}


Vue.prototype.formatShare = function(data) {
	console.log(data,'data---data');

	let userInfo = uni.getStorageSync('userInfo');
	var json = {},
		shareUser = userInfo['userId'],
		subAccountId = userInfo['subAccountId'],
		path = '/pages/beforeRouter/beforeRouter',
		title = '传播简单快乐，分享点滴生活',
		imageUrl = '',
		pathData = null,
		introduce='',
		productUserId = userInfo['productUserId'];
	if (data) {
		if (data.path && data.path != '/pages/fx_xjc/fx_xjc') {
			path = data.path;
		}
		if (data.title) {
			title = data.title;
		}
		if (data.data) {
			pathData = data.data;
		}
		if (data.introduce) {
			introduce = data.introduce;
		}
		if (data.imageUrl) {
			imageUrl = data.imageUrl;
		}
	}
	if (productUserId) {
		pathData.shareProductUserId = productUserId;
	}
	console.log('formatShare', pathData);
	console.log(data.type,'data.type----');
	if(data.type == 'dySpecial'){
		pathData.batchId = getApp().globalData.shareBatchId ? getApp().globalData.shareBatchId : '';
		if(uni.getStorageSync('shareWithBatchId')){
			pathData.batchId = getApp().globalData.batchId || uni.getStorageSync('nowBatchId');
		}
	}else{
		if(uni.getStorageSync('shareWithBatchId')){
			pathData.batchId = getApp().globalData.batchId || uni.getStorageSync('nowBatchId');
		}
		 if(getApp().globalData.shareBatchId){
				pathData.batchId = getApp().globalData.shareBatchId;
				if (pathData && pathData.compilationId) {
					let temp = JSON.parse(JSON.stringify(pathData));
					temp['compilationsId'] = temp['compilationId'];
					this.zwyRequest({
						url: '/cdp/spread_channel/batch/optimize',
						method: 'PUT',
						data: temp,
					}).then(res => {
						console.log('--------------/cdp/spread_channel/batch/optimize---------------', res);
					})
				}
		}
	}
	


	let pages = getCurrentPages(); //获取加载的页面
	let currentPage = pages[pages.length - 1]; //获取当前页面的对象
	let tempUrl = currentPage.route;

	if(data.path === '/pages/toTest/toTest') {
		path = '/pages/fx_xjc/fx_xjc'
	} else {
		path = tempUrl;
	}
	
	json.path = path + '?shareUser=' + shareUser + '&subAccountId=' + subAccountId;
	// #ifdef MP-KUAISHOU
	json.title = title;
	json.imageUrl = imageUrl;
	// #endif

	// #ifdef MP-TOUTIAO
	if(data.isFree == "WATCH_THE_ADS"){
		json.title = `免费看：${title}`;
		json.imageUrl = `https://res.qiguoread.com/staticResources/fellow_townsman/image/sPage_share1.png`
	} else{
		json.title = title;
		json.imageUrl = imageUrl;
	}
	// #endif
	
	json.desc = introduce

	// 挂链分享视频设置
	if(data.channel) {
		json.channel = data.channel
	}

	if(data.extra) {
		json.extra = data.extra
	}

	
	if (pathData) {
		for (var name in pathData) {
			json.path += '&' + name + '=' + pathData[name];
		}
	}
	console.log('formatShare111', json);
	return json;
}

Vue.prototype.getConfig = function() {
	return new Promise((resolve,reject)=>{
		
		if(getApp().globalData.config) {
			resolve(getApp().globalData.config);
			return;
		}
		let configUrl
		//#ifdef MP-KUAISHOU
		configUrl = getApp().globalData.extConfig.configUrl
		//#endif
		//#ifdef MP-TOUTIAO
		configUrl = '/attribute/config/CONFIG_JSON_FILE/267/133/4e3ef26dff83bac343a387269b35768c_1'
		let ttAccountInfo = tt.getEnvInfoSync() && tt.getEnvInfoSync().microapp
		if(ttAccountInfo && ttAccountInfo.appId) {
			let ttConfigMess = ttConfig[ttAccountInfo.appId]
			this.ttConfigMess = ttConfigMess
			configUrl = ttConfigMess.configUrl
		}
		//#endif
		this.zwyRequest({
			method: 'GET',
			url: `https://attribute-data.qiguoread.com${configUrl}?num=${Math.random()}`,
		}).then(res=>{
			if(res && res.config) {
				getApp().globalData.config = res.config;
				resolve(res.config);
			}
		})
	})
}


Vue.prototype.checkJujiVip = function(list) {
	if (!list || list.length == 0) return false;
	let tempIos = false;
	let tempCheck = false;
	for (let i = 0; i < list.length; i++) {
		if (list[i].releaseWay == 'VIP') {
			if (list[i].effectiveType == 'ALL_EFFECTIVE') tempCheck = true;
			else if (tempIos && list[i].effectiveType == 'IOS') tempCheck = true;
			else if (!tempIos && list[i].effectiveType != 'IOS') tempCheck = true;
		}
	}
	return tempCheck;
}

Vue.prototype.checkNeedLogin = function() {
	// //#ifdef MP-TOUTIAO
	// return false;
	// //#endif
	return true;
}

Vue.prototype.getClient = function() {
	return 'toutiao';
	
	//#ifdef MP-KUAISHOU
		return 'kuaishou';
	//#endif
	//#ifdef MP-TOUTIAO
		return 'toutiao';
	//#endif
}


Vue.prototype.zwyRequest = async function(postData) {
	let bufferBatchId =  uni.getStorageSync('bufferBatchId')
	let batchId = getApp().globalData.batchId || bufferBatchId || '';
	let spreadChannelId = getApp().globalData.spreadChannelId || '';
	let userInfo = uni.getStorageSync('userInfo') || '';
	if (typeof userInfo != 'object') {
		uni.removeStorageSync('userInfo');
		uni.removeStorageSync('alreadyAuthLogin');
		userInfo = ''; //111
	}
	let systemInfo = null
	//#ifdef MP-KUAISHOU
	systemInfo = await uni.getSystemInfoSync();
	//#endif
	//#ifdef MP-TOUTIAO
	systemInfo = await tt.getSystemInfoSync();
	//#endif
	let version = '3.30.5.1213'
	let accountInfo;
	let clientId = '';
	//#ifdef MP-KUAISHOU
		accountInfo = uni.getAccountInfoSync();
		if (accountInfo && accountInfo.miniProgram && accountInfo.miniProgram.version) version = accountInfo.miniProgram.version;
		clientId =  getApp().globalData.extConfig['clientId'];
	//#endif
	//#ifdef MP-TOUTIAO
		if(tt.getEnvInfoSync) accountInfo = tt.getEnvInfoSync();
		if (accountInfo && accountInfo.plugin && accountInfo.plugin.version) version = accountInfo.plugin.version;
		clientId =  this.clientInfo['client-id-online'];
	//#endif
	
	let header = {
		'content-type': 'application/json', // 默认值
		'os-type': systemInfo && systemInfo['model'] && systemInfo['model'].indexOf('iPhone') == -1 ? '1' : '2',
		'client-id': clientId,
		'sub-user-id': userInfo && userInfo.subAccountId ? String(userInfo.subAccountId) : '0',
		'user-id': userInfo && userInfo.userId ? String(userInfo.userId) : '0',
		'user-token': userInfo && userInfo.userToken ? String(userInfo.userToken) : '',
		'app-id': uni.getStorageSync('appId') || '',
		'c-type': this.clientInfo['c-type'],
		'open-id': userInfo && userInfo.authUserDTO ? String(userInfo.authUserDTO.openId) : '',
		'version-str': version,
		'scene': getApp().globalData.scene ? String(getApp().globalData.scene) : '0'
	};
	if(userInfo && userInfo.productUserId) {
		header['product-user-id'] = userInfo.productUserId
	}

	let newVideoCompilationId = uni.getStorageSync('newVideoCompilationId')
	if(newVideoCompilationId) {
		header['compilations-id'] = newVideoCompilationId
	}

	//#ifdef MP-TOUTIAO
	if(systemInfo && systemInfo.appName) {
		header['app-name'] = systemInfo.appName
	}
	if(getApp().globalData.adPlanParma.promotionId) {
		header['ad-plan-id'] = getApp().globalData.adPlanParma.promotionId
	}
	//#endif
	//#ifdef MP-KUAISHOU
	if(getApp().globalData.adPlanParma.aid || getApp().globalData.adPlanParma.ksUnitId) {
		header['ad-plan-id'] = getApp().globalData.adPlanParma.aid || getApp().globalData.adPlanParma.ksUnitId
	}
	//#endif
	let urlObj = this.clientInfo['urlObj-online'];
	if (getApp().globalData.PROFILE == 'online') {

	} else if (getApp().globalData.PROFILE == 'dev') {
		header['client-id'] = this.clientInfo['client-id-test'];
		//测试服
		urlObj = this.clientInfo['urlObj-test'];
	} else if (getApp().globalData.PROFILE == 'qa') {
		//QA环境
		urlObj = this.clientInfo['urlObj-qa'];
	}

	if(getApp().globalData.templateMessageTaskId && getApp().globalData.templateMessageTaskType) {
		header['template-message-task-id'] = getApp().globalData.templateMessageTaskId
		header['template-message-task-type'] = getApp().globalData.templateMessageTaskType
	}
	
	if(getApp().globalData.chainId) {
		header['chain-id'] = getApp().globalData.chainId
	}
	if (batchId) header['batch-id'] = batchId;
	if (spreadChannelId) header['spread-channel-id'] = String(spreadChannelId);
	let postUrl = postData.url;
	if (postUrl.indexOf('http') == -1) {
		if(postData.isReport) { // 上报日志特殊处理
			postUrl = urlObj['report'] + postData.url
		} else {
			let tempArr = postData.url.split('/')
			postUrl = urlObj[tempArr[1]] + postData.url
		}
	}
	if (postData['method']) postData['method'] = postData['method'].toUpperCase();


	return new Promise((resolve, reject) => {
		/* if(未登录 && 不是快手登陆请求 && 不是抖音登陆请求 && 登陆失败次数小于3 && 检查应用是否需要登录){
			将请求和resolve放入队列中，先调用登陆
			return;
		 }
		*/ 
		if (!header['user-token'] && (postUrl.indexOf('user/kuaishou_login/kuaishou_mini_program') == -
			1 && postUrl.indexOf('user/douyin/mini_program') == -
			1) && getApp().globalData.loginFail < 3 && this.checkNeedLogin()) {
			postData['resolve'] = resolve
			getApp().globalData.zwyQueue.push(postData);
			console.log('请求放入队列', postUrl);
			if (!getApp().globalData.isLogining) this.zwyLogin();
			return;
		}
		let headerAfter = (postData || {}).header ? {
			...header,
			...postData.header
		} : header
		uni.request({
				method: 'GET',
				...postData,
				header: headerAfter,
				url: postUrl,
			})
			.then(res => {
				let tempRes = ''
				if(postUrl.indexOf('global_vip_open') !== -1) { // 特殊处理下布尔类型的大会员
					tempRes = res[1] && res[1].data ? res[1].data : {}
				} else if(postUrl.indexOf('getActivityRewards') !== -1) {
					tempRes = res[1] && res[1].data ? res[1].data : '0'
				}else if (postUrl.indexOf('/wealth/api/activity_pay/platform/pop_ups_retrieve') !== -1) {
					tempRes = res[1]
				} else if (postUrl.indexOf('/douYin/coupons/verification') !== -1) {
					tempRes = res[1] && res[1].data ? res[1].data : {}
				}else {
					tempRes = res[1] && res[1].data && res[1].data.data ? res[1].data.data : res[1] && res[1].data ? res[1].data : {}
				}
				console.log(`tempRes:${postUrl}`, tempRes);
				if (!tempRes) {
					this.errorPopup(postUrl, headerAfter, tempRes)
					if (!postData.resolve) resolve(false);
					else postData.resolve(false);
					return;
				}
				if (this.checkNeedLogin() && ((tempRes.msg && tempRes.msg.indexOf('用户未登录') != -1 &&
					getApp().globalData.loginFail < 3) || res[1].header['logout-status'])) 
				{
					uni.removeStorageSync('userInfo');
					uni.removeStorageSync('alreadyAuthLogin');
					postData['resolve'] = resolve;
					getApp().globalData.zwyQueue.push(postData);
					if (!getApp().globalData.isLogining) this.zwyLogin();
					return;
				}
				
				if (tempRes.msg) {
					console.error(`
						postUrl:${postUrl},
						zwyRequest:111----${tempRes.msg}
					`)
					this.errorPopup(postUrl, headerAfter, tempRes)
					if(postUrl.indexOf('api/pay_client/top_up_preorder') !== -1) {
						uni.hideLoading()
						setTimeout(() => {
							uni.showToast({
								title: tempRes.msg,
								icon: 'none'
							})	
						}, 300)
					}
					if (!postData.noErr && this.checkNeedLogin()) {
						uni.showToast({
							title: tempRes.msg,
							icon: 'none'
						})
					}
					resolve(false);
					return;
				}
				if (!postData.resolve) resolve(tempRes);
				else postData.resolve(tempRes);
			})
			.catch(error => {
				console.log(`
					postUrl:${postUrl},
					zwyRequesterror:222----${JSON.stringify(error)}
				`)
				this.errorPopup(postUrl, headerAfter, error)
				uni.showToast({
					title: `${postUrl}接口请求失败:${error}`,
					icon: 'none'
				})
				reject(error);
			})
	})
}

Vue.prototype.zwyRouter = function(zwyUrl) {
	console.log('zwyUrl', zwyUrl);
	let tempPage = getCurrentPages();
	let tempTabList = ['pages/fx_xjc/fx_xjc', 'pages/mine/mine', 'pages/hj_history/hj_history'];
	let check = false;
	tempTabList.forEach((isItem) => {
		if (zwyUrl.indexOf(isItem) <= 2 && zwyUrl.indexOf(isItem) != -1) check = true;
	})
	if (check) {
		uni.switchTab({
			url: zwyUrl
		})
		return;
	}
	if (tempPage.length >= 6) {
		uni.redirectTo({
			url: zwyUrl,
		})
	} else {
		console.log('zwyUrl', zwyUrl);
		uni.navigateTo({
			url: zwyUrl,
		})
	}
}

// 获取群口令配置
Vue.prototype.getWardConfig = function(type, platform, useDepartment,diversionSceneType = 0) {
	return new Promise((resolve, reject) => {
		this.zwyRequest({
			method: 'GET',
			url: `/welfare/word/getJoinGroupWord?type=${type}&owningPlatform=${platform}&useDepartment=${useDepartment || 0}&diversionSceneType=${diversionSceneType}`
		}).then(res=>{
			resolve(res || {})
		})
	})
}

// 群复制成功传递回调值
Vue.prototype.callBackWardCopy = function(id) {
	if(!id) return
	return new Promise((resolve, reject) => {
		this.zwyRequest({
			method: 'GET',
			url: `/welfare/word/callback?id=${id}`
		}).then(res=>{
			resolve(res)
		})
	})
}


// 抖音获取配置信息
Vue.prototype.getConfigDouyin = function() {
	return new Promise((resolve,reject)=>{
		
		if(getApp().globalData.config) {
			resolve(getApp().globalData.config);
			return;
		}
		
		let ttAccountInfo = tt.getEnvInfoSync() && tt.getEnvInfoSync().microapp
		let copyType = ''
		let ttConfigMess = ''
		if(ttAccountInfo && ttAccountInfo.appId) {
			ttConfigMess = ttConfig[ttAccountInfo.appId]
			copyType = ttConfigMess.copyType
		}
		console.log('res.config-------------', ttConfigMess)
		let url = `https://ad.jinbiaozhi.com${ttConfigMess.configUrl}` || 'https://ad.jinbiaozhi.com/attribute/config/CONFIG_JSON_FILE/128/273/6f28d7a0dfe27365768b9b74aa8fc216_1'
		this.zwyRequest({
			method: 'GET',
			url: `${url}?num=${Math.random()}`
		}).then(res=>{
			if(res && res.config) {
				getApp().globalData.config = res.config;
				resolve(res.config);
			}
		})
	})
}

// 快手获取json配置信息
Vue.prototype.getConfigKs = function() {
	return new Promise((resolve,reject)=>{
		console.log('ksAccountInfo----------------------', getApp().globalData.config)
		if(getApp().globalData.config) {
			resolve(getApp().globalData.config);
			return;
		}
		
		let ksAccountInfo = uni.getAccountInfoSync();
		if (ksAccountInfo && ksAccountInfo.miniProgram) ksAccountInfo = ksAccountInfo.miniProgram;
		console.log('ksConfigItem-------------------', ksAccountInfo)


		let ksConfigItem = ksConfigAll[ksAccountInfo.appId]
		let url = `https://attribute-data.qiguoread.com${ksConfigItem.configUrl}` || '/attribute/config/CONFIG_JSON_FILE/499/154/bbfe1ebfbe5edcaebf319a725451030a_1'
		this.zwyRequest({
			method: 'GET',
			url: `${url}?num=${Math.random()}`
		}).then(res=>{
			if(res && res.config) {
				getApp().globalData.config = res.config;
				resolve(res.config);
			}
		})
	})
}

Vue.prototype.updateAppManager = function() {
    try {
        const updateManager = uni.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log('版本更新---', res.hasUpdate)
        })
        updateManager.onUpdateReady(function () {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
             uni.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: function (res) {
                    if (res.confirm) {
                        updateManager.applyUpdate()
                    }
                }
            });

        })
        updateManager.onUpdateFailed(function () {
           // 新版本下载失败
            console.log('download error');
        })
        // 每隔一个小时主动检查更新一次
        setInterval(() => updateManager.triggerCheckUpdate(), 60*60*1000)
    } catch (error) {
        console.log(`getUpdateManager fail: ${JSON.stringify(error)}`);
    }
}

Vue.prototype.errorPopup = async function(postUrl, headerAfter, error, type) {
	let res = await uni.getNetworkType()
	let sysMess = await uni.getSystemInfo()
	let errorAfter = error || {}
	let obj = {
		errorType: 1,
		logLevel: type || 3,
		networkEnv: (res[1] || {}).networkType || '未知',
		mobile: (sysMess[1] || {}).model || '未知',
		postUrl: postUrl,
		...errorAfter
	}
	this.zwyRequest({
		method: 'POST',
		url: `/error_push`,
		isReport: true,
		header: headerAfter,
		data: JSON.stringify(obj)
	})
}

Vue.prototype.errorPopupVideo = async function(data) {
	let obj = {
		errorType: 2,
		...data
	}
	this.zwyRequest({
		method: 'POST',
		url: `/error_push`,
		isReport: true,
		data: JSON.stringify(obj)
	})
}

// 时间对比
function timeChangeSet (time, afterTime) {
	const text = {}
	if (!time || !afterTime) return text
	const newTime = new Date(time)
	const oldTime = new Date(afterTime)
	const diffTime = (newTime - oldTime) / 1000

	const days = parseInt(diffTime / 86400)
	const hours = parseInt(diffTime / 3600) - 24 * days
	const minutes = parseInt(diffTime % 3600 / 60)
	const seconds = parseInt(diffTime % 3600 % 60)
	return {
		diffTime,
		days,
		hours,
		minutes,
		seconds
	}
}

const app = new Vue({
	...App,
	store
})
app.$mount()
